package org.example.hypersonaltools.tool;

import java.io.*;


public class GetDllTool {
    public static File getDllPath(String filename) throws IOException {

        String systemType = System.getProperty("os.name");
        String fileExt = (systemType.toLowerCase().indexOf("win")!= -1) ? ".dll" :".so";
        File path = new File(".");
        //将所有动态链接库d11/so文件都放在一个临时文件夹下,然后进行加载
        //这是应为项目为可执行jar文件的时候不能很方便的扫描里面文件
        //此目录放置在与项目同目录下的natives文件夹下
        String sysUserTempDir = path.getAbsoluteFile().getParent() + File.separator+"lib";
        System.out.println("----->>nativelibla时存放目录: "+sysUserTempDir);
        String fileName = filename + fileExt;
        InputStream in = null;
        BufferedInputStream reader = null;
        FileOutputStream writer = null;
        File tempFile = new File(sysUserTempDir + File.separator + fileName);
        if(!tempFile.getParentFile().exists())
            tempFile.getParentFile().mkdirs();
        if (tempFile.exists()) {
            tempFile.delete();
        }

        try {
//读取文件形成输入流
            in = GetDllTool.class.getResourceAsStream("/lib/" + fileName);
            if (in == null)
                in = GetDllTool.class.getResourceAsStream("lib/" + fileName);
            GetDllTool.class.getResource(fileName);
            reader = new BufferedInputStream(in);
            writer = new FileOutputStream(tempFile);
            byte[] buffer = new byte[1024];
            while (reader.read(buffer) > 0) {
                writer.write(buffer);
                buffer = new byte[1024];
            }
        }catch(IOException e){
            e.printStackTrace();
        } finally {
            try {
                if(in != null)
                    in.close();
                if (writer != null)
                    writer.close();
            } catch (IOException e) {
                e.printStackTrace();
                System.load(tempFile.getPath());
                System.out.println("----->>加载native文件:" + tempFile + "成功!!");
            }
        }
        return tempFile;
    }

}


